package com.gmail.cristiandeives.homingpigeon;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.ComponentName;
import android.preference.Preference;
import android.preference.PreferenceManager;
import android.telephony.PhoneNumberUtils;

public class HomingPigeonChangeListener implements Preference.OnPreferenceChangeListener {
    private Activity mParentActivity;

    public HomingPigeonChangeListener(Activity parent) {
        mParentActivity = parent;
    }

    @Override
    public boolean onPreferenceChange(Preference enabledPref, Object newEnabled) {
        Context ctx = enabledPref.getContext();
        boolean enabled = (Boolean) newEnabled;
        if (enabled) {
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(ctx);
            String currentPhoneNumber = prefs.getString(HomingPigeonApplication.PHONE_NUMBER_ID, null);
            if (currentPhoneNumber == null || !PhoneNumberUtils.isWellFormedSmsAddress(currentPhoneNumber)) {
                mParentActivity.showDialog(HomingPigeonApplication.DIALOG_INVALID_PHONE_NUMBER_ID);
                return false;
            }
        }

        PackageManager pm = ctx.getPackageManager();
        ComponentName receiver = new ComponentName(ctx, SmsWatcher.class);
        int enabledSetting = enabled
                ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED
                : PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
        pm.setComponentEnabledSetting(receiver, enabledSetting, PackageManager.DONT_KILL_APP);

        return true;
    }
}
